package com.sam.springboot.algorithm;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @classname: RoundRobin
 * @description: 普通轮询算法
 * 按顺序依次循环分配
 * @Author: sam
 * @date: 2022/5/21 10:21
 */
@Slf4j
public class RoundRobin {

    private static AtomicInteger index = new AtomicInteger(0);
    private static List<String> nodes = new ArrayList<>();

    /**
     * 初始化节点
     */
    static {
        nodes.add("192.168.0.1");
        nodes.add("192.168.0.2");
        nodes.add("192.168.0.3");
        log.info("初始化节点:{}",nodes);
    }

    public synchronized String selectNode(){
        String ip = null;
        // 下标复位
        if(index.get()>=nodes.size()) index.set(0);
        ip = nodes.get(index.getAndIncrement());

        log.info("{}--获取节点：{}",Thread.currentThread().getName(),ip);
        return ip;
    }

    public static void main(String[] args) {
        new Thread(()->{
            RoundRobin roundRobin = new RoundRobin();
            for (int i=1;i<=10;i++){
                String serverIp = roundRobin.selectNode();
                //log.info("{}--第{}次获取节点：{}",Thread.currentThread().getName(),i,serverIp);
            }
        }).start();

        /*new Thread(()->{
            RoundRobin roundRobin = new RoundRobin();
            for (int i=0;i<=5;i++){
                String serverIp = roundRobin.selectNode();
                log.info("{}--第{}次获取节点：{}",Thread.currentThread().getName(),i,serverIp);
            }
        }).start();*/

        RoundRobin roundRobin2 = new RoundRobin();
        for (int i=1;i<=10;i++){
            String serverIp = roundRobin2.selectNode();
            //log.info("{}--第{}次获取节点：{}",Thread.currentThread().getName(),i,serverIp);
        }
    }
}
